package com.example.barry.pdf;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ReplacementTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



import com.example.barry.pdf.Utils.Help;
import com.example.barry.pdf.Utils.WebServiceUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by barry on 17-1-16.
 */

public class MasterActivity extends Activity{

    private MyApplication myApplication ;
    private String deviceid = "";
    private String localip = "";
    private ListView listView;
    private String url = "";
    private String total = "";
    private ArrayAdapter<String> adapter;
    private Button send;
    private List<String> list = new ArrayList<String>();
    private TextView textView;
    private List<String> URLlist = new ArrayList<String>();
    private Socket socket;
    private StartThread st;
    private Help help = new Help();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_master);
        myApplication = (MyApplication) getApplication();
        localip = myApplication.getLocal();
        deviceid = myApplication.getDeviceID();
        listView = (ListView) findViewById(R.id.list_view);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
        listView.setAdapter(adapter);
        send = (Button) findViewById(R.id.send);
        textView = (TextView) findViewById(R.id.et);
        init();
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 WebServiceUtils.callSendAutoSFDCService(WebServiceUtils.WEB_SERVER_URL, "sendAutoSFDC", new Object[]{new String(textView.getText().toString().toUpperCase()), new String(deviceid), new String("172.26.100.230"), new Integer("18000"),new Boolean(true)}, new WebServiceUtils.WebServiceCallBack() {
                    //WebService接口返回的数据回调到这个方法中
                    public void callBack(final SoapObject result) {
                        String[] aa = help.parseSoapObject(result);
                        Log.i("aa的长度",aa.length+"");
                            if (aa.length > 1&&aa[1].equals("Serial Number?") ){
                                WebServiceUtils.callSendAutoSFDCService(WebServiceUtils.WEB_SERVER_URL, "querySerialInfo", new Object[]{new String(textView.getText().toString().toUpperCase()), new Integer(deviceid)}, new WebServiceUtils.WebServiceCallBack() {
                                    @Override
                                    public void callBack(SoapObject result) {
                                        String[] s = help.parseQuerySerialInfo(result);
                                        String portalhost = myApplication.getPortalhost();
                                        String plantcode = myApplication.getPlantcode();
                                        Log.i("12","12");
                                        final String path = "http://"+portalhost+"/sfdc-portlet/queryDoc?"+plantcode+"&"+s[5]+"&"+
                                                s[7]+"&sfdcHost=172.26.100.230";
                                        Log.i("path",path);
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try{
                                                    String temp =  help.getJsonString(path);
                                                    JSONObject jsonPath= new JSONObject(temp);
                                                    total = jsonPath.getString("total");
                                                    Log.i("total",total);
                                                    Message msg0 = handler.obtainMessage();
                                                    msg0.what = 3;
                                                    msg0.obj = total;
                                                    handler.sendMessage(msg0);
                                                    if(total.equals("0")){
                                                    }else {
                                                        JSONArray jsonArrayDos = jsonPath.getJSONArray("docs");
                                                        for (int i = 0; i < jsonArrayDos.length(); i++){
                                                            JSONObject object = (JSONObject) jsonArrayDos.get(i);
                                                            url = object.getString("url");
                                                            URLlist.add(url);
                                                        }
                                                        //      Log.i("URL集合",""+URLlist);
                                                        Message msg = handler.obtainMessage();
                                                        msg.what = 1;
                                                        msg.obj = URLlist;
                                                        handler.sendMessage(msg);
                                                    }
                                                }catch (Exception e){
                                                          Log.i("解析URL",e.getMessage());
                                                }
                                            }
                                        }).start();

                                    }
                                });
                            }
                        list.add(textView.getText().toString().toUpperCase());
                        textView.setText("");
                        list.add(aa[1]);
                        String s = aa[0];
                        String ss = s.substring(2);
                        list.add(ss);
                        adapter.notifyDataSetChanged();

                    }
                });
            }
        });
    }
    private void init() {
        //通过工具类调用WebService接口
      WebServiceUtils.callSendAutoSFDCService(WebServiceUtils.WEB_SERVER_URL, "sendAutoSFDC", new Object[]{new String("RESET"), new String(deviceid), new String("172.26.100.230"), new Integer("18000"),new Boolean(true)}, new WebServiceUtils.WebServiceCallBack() {
            //WebService接口返回的数据回调到这个方法中
            public void callBack(final SoapObject result) {
                String[] aa = help.parseSoapObject(result);
                if (aa.length>1){
                    list.add(aa[1]);
                    String s = aa[0];
                    String ss = s.substring(2);
                    list.add(ss);
                    adapter.notifyDataSetChanged();
                }
            }
        });
        if (myApplication.getLocal().equals("")){

        }else {
            st = new StartThread();
            st.start();
        }
   /*     textView.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] originalCharArr = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
                return originalCharArr;
            }

            @Override
            protected char[] getReplacement() {
                char[] replacementCharArr = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
                return replacementCharArr;
            }
        });*/
    }
    Handler handler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case 1:
                    OutputStream os = null ;
                    try {
                        os = socket.getOutputStream();//得到socket的输出流
                        os.write((msg.obj.toString()+"\n").getBytes("utf-8"));

                    } catch (IOException e) {
                        e.printStackTrace();
                    }catch (Exception e){
                        Log.i("socket输出流异常",e.getMessage());
                    }
                    break;
                case 0:
                    displayToast("success");
                    break;
                case 2:
                    displayToast("服务器端未开启");
                    break;
                case 3:
                    displayToast(msg.obj+"份pdf文档");
                    break;
            }
        }
    };



    private void displayToast(String s)//Toast方法
    {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    private class StartThread extends Thread{
        @Override
        public void run() {
            try {
                socket = new Socket();
                socket.connect(new InetSocketAddress(localip, 30000), 1000);
              //  socket = new Socket(,30000);//连接服务端的IP
                if(socket.isConnected()){//成功连接获取socket对象则发送成功消息
                    Message msg0 = handler.obtainMessage();
                    msg0.what=0;
                    handler.sendMessage(msg0);
                }
            } catch (Exception e) {

            }
        }
    }
    public void onDestroy(){
        super.onDestroy();
        if (socket == null) {
            Log.i("socket","socket为NULL");
        } else {
            try {
                socket.getInputStream().close();
                socket.close();
            }catch (Exception e){
                Log.i("销毁socket",e.getMessage());
            }
        }
    }

}
